//
//  VVEmoticonTools.swift
//  Weibo
//
//  Created by 王惠平 on 2017/4/7.
//  Copyright © 2017年 Will Wang. All rights reserved.
//

import UIKit
import YYModel

//每页显示20个表情
let NumberofPage = 20

//最近解档和归档的路径
let RecentEmoticonArrayPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("recentEmotionArray.archive")


//表情工具类
class VVEmoticonTools: NSObject {
    
    //单例全局访问点
    static let sharedTools: VVEmoticonTools = VVEmoticonTools()
    
    //构造函私有化
    private override init() {
        super.init()
        
//        print(section(emoticonArray:defualtEmoticonArray))
//        print(emojiEmoticonArray.count)
//        print(lxhEmoticonArray.count)
       
    }

    //创建emoticonBudle对象
    lazy var emoticonBudle: Bundle = {
        
        //获取budle路径
        let bundlePath = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)!
        
        //根据路径创建budle对象
        let bundle = Bundle(path: bundlePath)!
        
        return bundle
        
    }()
    
    //默认表情
    fileprivate lazy var defualtEmoticonArray:[VVEmoticon] = {
        
        return self.getEmoticonArray(folderName: "default", fileName: "info.plist")
        
    }()
    
    //emoji表情
    fileprivate lazy var emojiEmoticonArray:[VVEmoticon] = {
        
        return self.getEmoticonArray(folderName: "emoji", fileName: "info.plist")
        
    }()
    
    //浪小花表情
    fileprivate lazy var lxhEmoticonArray:[VVEmoticon] = {
        
        return self.getEmoticonArray(folderName: "lxh", fileName: "info.plist")
        
    }()
    
    
    //最近表情
    fileprivate lazy var recentEmoticonArray:[VVEmoticon] = {
        
        if let localRecentEmoticonArray = self.loadRecentEmoticonArray() {
            
            //有本地最近表情数据
            return localRecentEmoticonArray
            
        } else {
            
             //没有本地表情数据
            let recentEmotionArray = [VVEmoticon]()
            
            return recentEmotionArray
        
        }
        
        
    }()
    
    //准备表情视图所需要的额数据
    lazy var allEmoticonArray:[[[VVEmoticon]]] = {
        
        return [
            
            //放入不同的二维数组
            //最近表情,只有一页
            [self.recentEmoticonArray],
            
            //默认表情
            self.section(emoticonArray: self.defualtEmoticonArray),
            
            //emoji表情
            self.section(emoticonArray: self.emojiEmoticonArray),
            
            //浪小花
            self.section(emoticonArray: self.lxhEmoticonArray),
            
            ]
    }()
    
    //根据传入的文件夹名和文件的名字获取对应的表情数据
    fileprivate func getEmoticonArray(folderName: String,fileName: String) ->[VVEmoticon] {
        
        //获取表情数据的子路径
        let subPath = folderName + "/" + fileName
        
        let path = self.emoticonBudle.path(forResource: subPath, ofType: nil)!
        
        //读取info.plist数据
        let dicArray = NSArray(contentsOfFile: path) as! [[String: Any]]
        
        //使用yymodel完成数组字典转成数组模型
        let modelArray = NSArray.yy_modelArray(with: VVEmoticon.self, json: dicArray) as![VVEmoticon]
        
        for model in modelArray {
            
            if model.type == "0" {
                
                //图片表情全路径
                let path = emoticonBudle.path(forResource: folderName, ofType: nil)! + "/" + model.png!
                
                //设置图片的全路径
                model.path = path
                
                //图片对应的文件
                model.folderName = folderName
            }
        }
        
        return modelArray
        
    }
    
    //计算每种表情分成都少页显示,并且完成每种表情对应成一个二维数组
    fileprivate func section(emoticonArray: [VVEmoticon])-> [[VVEmoticon]] {
        
        //根据传入的表情个数计算显示页数
        let pageCount = (emoticonArray.count - 1) / NumberofPage + 1
        
        var tempArray = [[VVEmoticon]]()
        
        for i in 0..<pageCount {
            
            //开始截取的索引
            let loc = i * NumberofPage
            
            //截取的长度
            var len = NumberofPage
            
            if loc + len > emoticonArray.count {
                
                //超出范围,截取剩余的个数
                len = emoticonArray.count - loc
                
            }
            
            //截取的范围
            let rang = NSMakeRange(loc, len)
            
            //根据范围截取子视图
            let subArray = (emoticonArray as NSArray).subarray(with: rang) as! [VVEmoticon]
            
            tempArray.append(subArray)
            
        }
        
        return tempArray
    }
    
    //保存点击的表情模型
    func saveRecentEmoticonArray(emoticon: VVEmoticon) {
        
        //判断最近表情里是否有要添加的表情模型
        for (i, currentEmoticon) in recentEmoticonArray.enumerated() {
            
            if emoticon.type == "0" {
                
                //图片表情,判断chs是否相同
                if currentEmoticon.chs == emoticon.chs {
                    
                    //有相同表情删除
                    recentEmoticonArray.remove(at: i)
                    
                    break
                }
                
            } else {
                
                //emoji表情,判断code是否相同
                if currentEmoticon.code == emoticon.code {
                    
                    //有相同表情删除
                    recentEmoticonArray.remove(at: i)
                    
                    break
                }
                
            }
        }
        
        //把点击的表情添加到数组的第一个元素的位置(最近使用的表情放到最前面)
        recentEmoticonArray.insert(emoticon, at: 0)
        
        if recentEmoticonArray.count > 20 {
            
            //如果最近表情个数大于20个删除最后一个元素
            recentEmoticonArray.removeLast()
        }
        
        //把allEmoticonArray的最近表情数据进行修改
        allEmoticonArray[0][0] = recentEmoticonArray
        
        //把最近的表情进行保存 (归档)
        NSKeyedArchiver.archiveRootObject(recentEmoticonArray, toFile: RecentEmoticonArrayPath)
        
        //让collectionView刷新最近的表情的这组数据

    }
    
    //获取最近表情数据
    func loadRecentEmoticonArray()-> [VVEmoticon]? {
        
        //解档数据
        let localArray = NSKeyedUnarchiver.unarchiveObject(withFile: RecentEmoticonArrayPath) as? [ VVEmoticon]
        
        return localArray
        
    }
    
    //根据表情描述获取表情模型
    func selectedEmoticon(chs: String) -> VVEmoticon? {
        
        //遍历默认表情数组查找表情模型
        for emoticon in defualtEmoticonArray {
            
            if emoticon.chs == chs {
                
                return emoticon
            }
            
        }
        
        //遍历浪小花表情数组查找表情模型
        for emoticon in lxhEmoticonArray {
            
            if emoticon.chs == chs {
                
                return emoticon
            }
        }
        
        return nil
    }
    
}
